/* ========================================================================= */
/* ------------------------------------------------------------------------- */
/*!
  \file			mainwindow.cc
  \date			Jul 2011
  \author		TNick

  \brief		Contains the implementation for MainWindow class


 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @n
 Please read ReadMe.txt and Licence.txt in root folder @n
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @n

*/
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
//
//
//
//
/*  INCLUDES    ------------------------------------------------------------ */

#include    <QFileDialog>
#include    <QStyleFactory>
#include    <QWhatsThis>
#include    <QSettings>
#include    <QMessageBox>
#include    <QCloseEvent>
#include    <QPrintDialog>
#include    <QPageSetupDialog>
#include    <QPainter>
#include    <QPrintPreviewDialog>
#include    <QDebug>


#include	"mainwindow.h"
#include	"ui_mainwindow.h"

/*  INCLUDES    ============================================================ */
//
//
//
//
/*  CLASS    --------------------------------------------------------------- */



/* ------------------------------------------------------------------------- */
MdiChild::MdiChild                              (void)
{
    is_untitled = true;
    is_closed = false;
    is_modified = false;
    cur_file = "";
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::newFile           (void)
{
    static int sequenceNumber = 1;

    is_untitled = true;
    cur_file = tr("document%1.txt").arg(sequenceNumber++);
    setWindowTitle(cur_file + "[*]");
    /*connect(document(), SIGNAL(contentsChanged()),
            this, SLOT(documentWasModified()));*/
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool                MdiChild::loadFile          (const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("Error"),
                             tr("Cannot read file %1:\n%2.")
                             .arg(fileName)
                             .arg(file.errorString()));
        return false;
    }

    //QTextStream in(&file);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    //setPlainText(in.readAll());
    QApplication::restoreOverrideCursor();

    setCurrentFile(fileName);

    /*connect(document(), SIGNAL(contentsChanged()),
            this, SLOT(documentWasModified()));*/

    return true;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool                MdiChild::save              (void)
{
    if (is_untitled)
        {
            return saveAs();
        }
    else
        {
            return saveFile(cur_file);
        }
}/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool                MdiChild::saveAs            (void)
{

    QFileDialog::Options options;
    QString selectedFilter;
    QString fileName = QFileDialog::getSaveFileName(
                this,
                tr("Select the location ..."),
                "",
                tr("All Files (*);;Text Files (*.txt)"),
                &selectedFilter,
                options);
    if (!fileName.isEmpty())
        {
            if (saveFile(fileName))
                {
                    emit nameChanged();
                    return true;
                }
        }
    return false;

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool                MdiChild::saveFile          (const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QFile::Text))
        {
            QMessageBox::warning(this, tr("MDI"),
                                 tr("Cannot write file %1:\n%2.")
                                 .arg(fileName)
                                 .arg(file.errorString()));
            return false;
        }

    //QTextStream out(&file);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    //out << toPlainText();
    QApplication::restoreOverrideCursor();

    setCurrentFile(fileName);
    return true;
}/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::closeEvent        (QCloseEvent *event)
{
    if (maybeSave())
        {
            event->accept();
            is_closed = true;
            emit docClosed(this);
        }
    else
        {
            event->ignore();
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool                MdiChild::maybeSave         (void)
{
    if (is_modified)
        {
            QMessageBox::StandardButton ret;
            ret = QMessageBox::warning(this, tr("Tell me..."),
                                       tr("'%1' has been modified.\n"
                                          "Do you want to save your changes?")
                                       .arg(userFriendlyCurrentFile()),
                                       QMessageBox::Save | QMessageBox::Discard
                                       | QMessageBox::Cancel);
            if (ret == QMessageBox::Save)
                return save();
            else if (ret == QMessageBox::Cancel)
                return false;
        }
    return true;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::setCurrentFile    (const QString &fileName)
{
    cur_file = QFileInfo(fileName).canonicalFilePath();
    is_untitled = false;
    is_modified = false;
    setWindowModified(false);
    setWindowTitle(userFriendlyCurrentFile() + "[*]");
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::pageSetupDialog   (void)
{
#ifndef QT_NO_PRINTER
    QPageSetupDialog set_pg(&printer, this);
    set_pg.exec();
#else
    QMessageBox::warning(this, tr("Error"),
                         tr("Print support was disabled at build time."));
#endif
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::printDialog       (void)
{
#ifndef QT_NO_PRINTER
    QPrintDialog dialog(&printer, this);
    dialog.setWindowTitle(tr("Print Document"));
    /*if (editor.textCursor().hasSelection())
        dialog.addEnabledOption(QAbstractPrintDialog::PrintSelection);*/
    if (dialog.exec() != QDialog::Accepted)
        return;
    print();
#else
    QMessageBox::warning(this, tr("Error"),
                         tr("Print support was disabled at build time."));
#endif
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::print             (void)
{
#ifndef QT_NO_PRINTER
    QPainter painter;
    painter.begin(&printer);
    /*
    for (int page = 0; page < numberOfPages; ++page) {

        // Use the painter to draw on the page.

        if (page != lastPage)
            printer.newPage();
    }
*/
    painter.end();
#endif
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void                MdiChild::printPreviewDialog    (void)
{
#ifndef QT_NO_PRINTER

    QPrintPreviewDialog preview(&printer, this);
    preview.setWindowFlags( Qt::Window );

    /*
    connect(&preview, SIGNAL(paintRequested(QPrinter *)),
            SLOT(printPreview(QPrinter *)));

    */
    preview.exec();

#else
    QMessageBox::warning(this, tr("Error"),
                         tr("Print support was disabled at build time."));
#endif
}
/* ========================================================================= */



/* ------------------------------------------------------------------------- */
MainWindow::MainWindow                          (QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->action_New,     SIGNAL(triggered()), this, SLOT(slot_New()));
    connect(ui->action_Open,    SIGNAL(triggered()), this, SLOT(slot_Open()));
    connect(ui->action_Save,    SIGNAL(triggered()), this, SLOT(slot_Save()));
    connect(ui->action_SaveAll, SIGNAL(triggered()), this, SLOT(slot_SaveAll()));
    connect(ui->action_SaveAs,  SIGNAL(triggered()), this, SLOT(slot_SaveAs()));
    connect(ui->action_Print,   SIGNAL(triggered()), this, SLOT(slot_Print()));
    connect(ui->action_PrintStUp, SIGNAL(triggered()), this, SLOT(slot_PrintStUp()));
    connect(ui->action_PrintPrev, SIGNAL(triggered()), this, SLOT(slot_PrintPreview()));
    connect(ui->action_Undo,    SIGNAL(triggered()), this, SLOT(slot_Undo()));
    connect(ui->action_Redo,    SIGNAL(triggered()), this, SLOT(slot_Redo()));
    connect(ui->action_Cut,     SIGNAL(triggered()), this, SLOT(slot_Cut()));
    connect(ui->action_Copy,    SIGNAL(triggered()), this, SLOT(slot_Copy()));
    connect(ui->action_Paste,   SIGNAL(triggered()), this, SLOT(slot_Paste()));
    connect(ui->action_Delete,  SIGNAL(triggered()), this, SLOT(slot_Delete()));
    connect(ui->action_SelAll,  SIGNAL(triggered()), this, SLOT(slot_SelAll()));
    connect(ui->action_No_skin, SIGNAL(triggered()), this, SLOT(slot_No_skin()));
    connect(ui->action_LoadStySh, SIGNAL(triggered()), this, SLOT(slot_LoadStySh()));
    connect(ui->action_LayDir,  SIGNAL(triggered()), this, SLOT(slot_LayDir()));
    connect(ui->action_About,   SIGNAL(triggered()), this, SLOT(slot_About()));
    connect(ui->action_Help,    SIGNAL(triggered()), this, SLOT(slot_Help()));
    connect(ui->action_HelpCtx, SIGNAL(triggered()), this, SLOT(slot_HelpCtx()));

    connect(ui->mdiArea,        SIGNAL(subWindowActivated(QMdiSubWindow*)),
            this, SLOT(slot_ActiveMdiChange(QMdiSubWindow*)));


    connect(ui->action_Close, SIGNAL(triggered()),
            ui->mdiArea, SLOT(closeActiveSubWindow()));
    connect(ui->action_CloseAll, SIGNAL(triggered()),
            ui->mdiArea, SLOT(closeAllSubWindows()));
    connect(ui->action_AboutQt, SIGNAL(triggered()),
            qApp, SLOT(aboutQt()));


    ui->statusbar->showMessage(tr("Ready"));


    /* list of MDI windows in menu */
    connect(ui->menuPanels, SIGNAL(triggered(QAction*)),
            this,SLOT(slot_ActiveMdiChange(QAction*)));
    connect(ui->action_Tile, SIGNAL(triggered()),
            ui->mdiArea, SLOT(tileSubWindows()));
    connect(ui->action_Cascade, SIGNAL(triggered()),
            ui->mdiArea, SLOT(cascadeSubWindows()));
    connect(ui->action_NextMdi, SIGNAL(triggered()),
            ui->mdiArea, SLOT(activateNextSubWindow()));
    connect(ui->action_PreviousMdi, SIGNAL(triggered()),
            ui->mdiArea, SLOT(activatePreviousSubWindow()));
    slot_UpdateWinMenu();

    /* main panel position and size */
    QSettings settings;
    QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
    QSize size = settings.value("size", QSize(400, 400)).toSize();
    move(pos);
    resize(size);


    /* recent files initialization */
    connect(ui->menuRecent_files, SIGNAL(triggered(QAction*)),
            this,SLOT(slot_RecentFile(QAction*)));

    settings.beginGroup("recent_files");
    rcnt_f_count = settings.value("::count::", 5).toUInt();
    QString s_crt;
    if (rcnt_f_count < 2) rcnt_f_count = 2;
    else if (rcnt_f_count > 50) rcnt_f_count = 50;
    for (int i = 0; i < rcnt_f_count; i++)
        {
            s_crt = settings.value(QString(i), "").toString();
            if (s_crt.isEmpty())
                break;
            rcnt_f.append(s_crt);
        }
    settings.endGroup();
    slot_UpdateRcFilesMenu();


    /* User interface templates */
    connect(ui->menuUITpl, SIGNAL(triggered(QAction*)),
            this,SLOT(slot_UItplChange(QAction*)));
    QStringList	sty_list = QStyleFactory::keys();
    for (int i = 0; i < sty_list.count(); i++)
        {
            QAction* act_in =  ui->menuUITpl->addAction(sty_list.at(i));
            act_in->setStatusTip(tr("Predefined skin"));
            act_in->setCheckable(true);
            if (qApp->style()->objectName().compare(
                        sty_list.at(i),Qt::CaseInsensitive))
                { /* a value diffrent from 0 means this is not it */
                    act_in->setChecked(false);
                }
            else
                {
                    act_in->setChecked(true);
                }
        }

    /* Skins (color schemes) */
    connect(ui->menuStySheet, SIGNAL(triggered(QAction*)),
            this,SLOT(slot_SkinChange(QAction*)));

    QDir	dir_ss(QCoreApplication::applicationFilePath());
    dir_ss.cd(QString("../StyleSheets"));
    if (dir_ss.exists())
        {
            QStringList filters;
            filters << "*.css";
            dir_ss.setNameFilters(filters);
            dir_ss.setFilter(QDir::NoDotAndDotDot | QDir::Files | QDir::Readable);
            filters = dir_ss.entryList();
            if (filters.count() > 0)
                {
                    for (int i = 0; i < filters.count(); i++)
                        {
                            QAction* act_in =
                                    ui->menuUITpl->addAction(sty_list.at(i));
                            act_in->setStatusTip(
                                        tr("StyleSheet located in "
                                           "application's predefined folder"));

                        }
                }
        }


    /* others */
    slot_ActiveMdiChange((QMdiSubWindow*)NULL);

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
MainWindow::~MainWindow	(void)
{
    /* execution never trully reaches here */
    delete ui;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_New            	(void)
{
    MdiChild *child = createMdiChild();
    child->newFile();
    child->show();
    slot_UpdateWinMenu();
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
bool        MainWindow::_open                   (QString s_file)
{
    QMdiSubWindow *existing = findMdiChild(s_file);
    if (existing)
        {
            ui->mdiArea->setActiveSubWindow(existing);
            return false;
        }

    MdiChild *child = createMdiChild();
    if (child->loadFile(s_file))
        {
            ui->statusbar->showMessage(tr("File loaded"), 2000);
            child->show();
            slot_UpdateWinMenu();
            addRecentFile(s_file);
            return true;
        }
    else
        {
            child->close();
        }
    return false;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_Open            	(void)
{
    QFileDialog::Options options;
    QString selectedFilter;
    QString fileName = QFileDialog::getOpenFileName(
                this,
                tr("Select the file to open..."),
                "",
                tr("All Files (*);;Text Files (*.txt)"),
                &selectedFilter,
                options);
    if (!fileName.isEmpty())
        {
            _open(fileName);
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_Save            	(void)
{
    MdiChild * mdic = activeMdiChild();
    if ((mdic != NULL) && (mdic->save()))
        {
            addRecentFile(mdic->currentFile());
            statusBar()->showMessage(tr("File saved"), 2000);
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_SaveAll            (void)
{
    foreach (QMdiSubWindow *window, ui->mdiArea->subWindowList())
        {
            MdiChild *mdiChild = qobject_cast<MdiChild *>(window);
            mdiChild->save();
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_SaveAs            	(void)
{
    MdiChild * mdic = activeMdiChild();
    if ((mdic != NULL) && (mdic->saveAs()))
        {
            addRecentFile(mdic->currentFile());
            statusBar()->showMessage(tr("File saved"), 2000);
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_Print            	(void)
{
    MdiChild* activem = activeMdiChild();
    if ((activem != NULL) && (!activem->closed()))
        {
            activem->printDialog();
        }

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_PrintStUp          (void)
{
    MdiChild* activem = activeMdiChild();
    if ((activem != NULL) && (!activem->closed()))
        {
            activem->pageSetupDialog();
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_PrintPreview    	(void)
{
    MdiChild* activem = activeMdiChild();
    if ((activem != NULL) && (!activem->closed()))
        {
            activem->printPreviewDialog();
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_Undo            	(void)
{
    MdiChild* activem = activeMdiChild();
    if (activem != NULL)
        {
            activem->undo();
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_Redo            	(void)
{
    MdiChild* activem = activeMdiChild();
    if (activem != NULL)
        {
            activem->redo();
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_Cut            	(void)
{
    MdiChild* activem = activeMdiChild();
    if (activem != NULL)
        {
            activem->cut();
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_Copy            	(void)
{
    MdiChild* activem = activeMdiChild();
    if (activem != NULL)
        {
            activem->copy();
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_Paste            	(void)
{
    MdiChild* activem = activeMdiChild();
    if (activem != NULL)
        {
            activem->paste();
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_Delete            	(void)
{
    MdiChild* activem = activeMdiChild();
    if (activem != NULL)
        {
            activem->delSel();
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_SelAll            	(void)
{
    MdiChild* activem = activeMdiChild();
    if (activem != NULL)
        {
            activem->selAll();
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_No_skin            (void)
{
    qApp->setStyleSheet(QString());
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::_loadStySh              (QString fileName)
{
    QString styleSheet;
    QFile   css_file;

    /* read file content */
    css_file.setFileName(fileName);
    if (!css_file.open(QFile::ReadOnly))
        {
            QMessageBox::warning(this, tr("Error"),
                                 tr("Cannot read file %1:\n%2.")
                                 .arg(fileName)
                                 .arg(css_file.errorString()));
            return;
        }
    styleSheet = QLatin1String(css_file.readAll());
    css_file.close();

    /* and load it's content */
    qApp->setStyleSheet(styleSheet);
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_LoadStySh          (void)
{
    QFileDialog::Options options;
    QString selectedFilter;
    QString fileName = QFileDialog::getOpenFileName(
                this,
                tr("Select style sheet to load ..."),
                QString(),
                tr("All Files (*);;Style sheets (*.css)"),
                &selectedFilter,
                options);
    if (!fileName.isEmpty())
        {
            _loadStySh(fileName);
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_LayDir            	(void)
{
    if (layoutDirection() == Qt::LeftToRight)
        qApp->setLayoutDirection(Qt::RightToLeft);
    else
        qApp->setLayoutDirection(Qt::LeftToRight);

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_About            	(void)
{
    QMessageBox::about(this, tr("About app"),
                       tr("The <b>App</b> ...."));
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_Help            	(void)
{
    QMessageBox::about(this, tr("Help"),
                       tr("Help system is not implemented yet."));
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_HelpCtx            (void)
{
    QWhatsThis::enterWhatsThisMode();
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_ActiveMdiChange    (MdiChild* p_active)
{
    /* stupid */
    slot_ActiveMdiChange(qobject_cast<QMdiSubWindow*>(p_active));
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_ActiveMdiChange    (QMdiSubWindow* p_active)
{
    Q_UNUSED(p_active);

    MdiChild* activem = activeMdiChild();
    bool sel_dep = false;
    bool file_dep = false;

    QList<QMdiSubWindow*> list = ui->mdiArea->subWindowList();

    for (int i = 0; i < list.size (); i++)
        {
            MdiChild *child = qobject_cast<MdiChild *>(list.at(i));

            if (!child->closed())
                {
                    if (activem != NULL)
                        {
                            sel_dep = activem->hasSelection();
                        }
                    file_dep = true;
                    break;
                }
        }


    ui->action_Cut->setEnabled(sel_dep);
    ui->action_Copy->setEnabled(sel_dep);
    ui->action_Delete->setEnabled(sel_dep);

    ui->action_Paste->setEnabled(file_dep);
    ui->action_SaveAll->setEnabled(file_dep);
    ui->action_Save->setEnabled(file_dep);
    ui->action_SaveAs->setEnabled(file_dep);
    ui->action_Close->setEnabled(file_dep);
    ui->action_CloseAll->setEnabled(file_dep);
    ui->action_Print->setEnabled(file_dep);
    ui->action_PrintStUp->setEnabled(file_dep);
    ui->action_PrintPrev->setEnabled(file_dep);
    ui->action_Undo->setEnabled(file_dep);
    ui->action_Redo->setEnabled(file_dep);
    ui->action_SelAll->setEnabled(file_dep);
    ui->action_Tile->setEnabled(file_dep);
    ui->action_Cascade->setEnabled(file_dep);
    ui->action_NextMdi->setEnabled(file_dep);
    ui->action_PreviousMdi->setEnabled(file_dep);
    ui->menuPanels->setEnabled(file_dep);

    sel_dep = ui->action_Save->isEnabled();
    if (file_dep != sel_dep)
        {
            file_dep = 0;
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_ActiveMdiChange    (QAction* p_active)
{
    QList<QAction *> acls = ui->menuPanels->actions();
    int i = acls.indexOf(p_active);
    if (i < 0) return;
    QList<QMdiSubWindow*> list = ui->mdiArea->subWindowList();
    if (i >= list.count()) return;
    foreach (QAction *act_m, acls)
        {
            act_m->setChecked(false);
        }
    p_active->setChecked(true);
    ui->mdiArea->setActiveSubWindow(list.at(i));
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_RecentFile         (QAction* p_active)
{
    QList<QAction *> acls = ui->menuRecent_files->actions();
    int i = acls.indexOf(p_active);
    if (i < 0) return;
    if (i >= rcnt_f.count()) return;

    _open(rcnt_f.at(i));

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_UItplChange        (QAction* p_active)
{
    foreach(QAction* qa, ui->menuUITpl->actions())
        {
            qa->setChecked(false);
        }
    p_active->setChecked(true);
    qApp->setStyle(p_active->text());
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_SkinChange         (QAction* p_active)
{
    QList<QAction *> acls = ui->menuStySheet->actions();
    int i = acls.indexOf(p_active);
    if (i < 2) return;

    QDir	dir_ss(QCoreApplication::applicationFilePath());
    dir_ss.cd(QString("../StyleSheets"));
    if (dir_ss.exists())
        {
            _loadStySh(dir_ss.absoluteFilePath(p_active->text()));
        }

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_SelStateChange     (void)
{
    MdiChild* activem = activeMdiChild();
    bool sel_dep = false;

    if (activem != NULL)
        {
            sel_dep = activem->hasSelection();
        }
    ui->action_Cut->setEnabled(sel_dep);
    ui->action_Copy->setEnabled(sel_dep);
    ui->action_Delete->setEnabled(sel_dep);

}
/* ========================================================================= */


/* ------------------------------------------------------------------------- */
void        MainWindow::closeEvent              (QCloseEvent *event)
{
    QSettings settings;

    QList<QMdiSubWindow*> list = ui->mdiArea->subWindowList();

    for (int i = 0; i < list.size (); i++)
        {
            MdiChild *child = qobject_cast<MdiChild *>(list.at(i));

            if (!child->closed())
                {
                    if (!list[i]->close())
                        {
                            event->ignore();
                            return;
                        }
                }
        }
    settings.setValue("pos", pos());
    settings.setValue("size", size());
    event->accept ();

    /* recent files initialization */
    int       i;
    if (rcnt_f_count < 2) rcnt_f_count = 2;
    else if (rcnt_f_count > 50) rcnt_f_count = 50;
    settings.beginGroup("recent_files");
    settings.setValue("::count::", rcnt_f_count);
    for (i = 0; i < rcnt_f_count; i++)
        {
            if (i >= rcnt_f.count())
                break;
            settings.setValue(QString(i), rcnt_f.at(i));
        }
    settings.setValue(QString(i), "");
    settings.endGroup();
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::cleanMDILeftovers       (void)
{
    QList<QMdiSubWindow*> list = ui->mdiArea->subWindowList();

    for (int i = 0; i < list.size (); i++)
        {
            MdiChild *child = qobject_cast<MdiChild *>(list.at(i));

            if (child->closed())
                {
                    delete  child;
                }
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
MdiChild *  MainWindow::createMdiChild          (void)
{
    cleanMDILeftovers();

    MdiChild *child = new MdiChild;
    ui->mdiArea->addSubWindow(child);
    connect(child,SIGNAL(docClosed(MdiChild*)),
            this,SLOT(slot_UpdateWinMenu()));
    connect(child,SIGNAL(nameChanged()),
            this,SLOT(slot_UpdateWinMenu()));
    connect(child,SIGNAL(docClosed(MdiChild*)),
            this,SLOT(slot_ActiveMdiChange(MdiChild*)));
    connect(child,SIGNAL(selStateChange()),
            this,SLOT(slot_SelStateChange()));
    return child;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_UpdateWinMenu      (void)
{
    ui->menuPanels->clear();
    QList<QMdiSubWindow *> windows = ui->mdiArea->subWindowList();

    if (windows.count() == 0)
        {
            ui->menuPanels->addAction(tr("(none)"));
            return;
        }
    for (int i = 0; i < windows.count(); ++i)
        {
            MdiChild *child = qobject_cast<MdiChild *>(windows.at(i));
            if (!child->closed())
                {
                    QString text;
                    if (i < 9)
                        {
                            text = tr("&%1 %2").arg(i + 1)
                                    .arg(child->userFriendlyCurrentFile());
                        }
                    else
                        {
                            text = tr("%1 %2").arg(i + 1)
                                    .arg(child->userFriendlyCurrentFile());
                        }
                    QAction *action  = ui->menuPanels->addAction(text);
                    action->setCheckable(true);
                    action->setChecked(child == activeMdiChild());
                }
        }
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::slot_UpdateRcFilesMenu  (void)
{
    ui->menuRecent_files->clear();

    if (rcnt_f.count() == 0)
        {
            ui->menuRecent_files->addAction(tr("(none)"));
            return;
        }

    for (int i = 0; i < rcnt_f.count(); ++i)
        {
            QAction *action  = ui->menuRecent_files->addAction(
                        QFileInfo(rcnt_f.at(i)).fileName());
            action->setToolTip(rcnt_f.at(i));
        }

}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
MdiChild *  MainWindow::activeMdiChild          (void)
{
    MdiChild * pactive =
            qobject_cast<MdiChild *>(ui->mdiArea->activeSubWindow());
    if (pactive != NULL)
        {
            if (pactive->closed() == FALSE)
                return pactive;
        }
    return NULL;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
QMdiSubWindow *MainWindow::findMdiChild         (const QString &fileName)
{
    QString canonicalFilePath = QFileInfo(fileName).canonicalFilePath();

    foreach (QMdiSubWindow *window, ui->mdiArea->subWindowList())
        {
            MdiChild *mdiChild = qobject_cast<MdiChild *>(window);//->widget()
            if (!mdiChild->closed())
                {
                    if (mdiChild->currentFile() == canonicalFilePath)
                        return window;
                }
        }
    return NULL;
}
/* ========================================================================= */

/* ------------------------------------------------------------------------- */
void        MainWindow::addRecentFile           (QString s_file)
{
    int i = rcnt_f.indexOf(s_file);
    if (i != -1)
        {
            rcnt_f.move(i, 0);
        }
    else
        {
            if (rcnt_f.count() >= rcnt_f_count)
                {
                    rcnt_f.removeLast();
                }
            rcnt_f.prepend(s_file);
        }
    slot_UpdateRcFilesMenu();
}
/* ========================================================================= */


/*  CLASS    =============================================================== */
//
//
//
//
/* ------------------------------------------------------------------------- */
/* ========================================================================= */
